/*

    Licensed under the Apache License, Version 2.0 (the "License"); 
    you may not use this file except in compliance with the License. 
    You may obtain a copy of the License at 
    http://www.apache.org/licenses/LICENSE-2.0 
    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    See the License for the specific language governing permissions and 
    limitations under the License.
      
 */

package jforex.mql.converter;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.RepaintManager;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

/**
 * Sample login dialog
 */
@SuppressWarnings("serial")
public class ConverterGUI extends JDialog implements ActionListener {

    private String CMD_CANCEL = "cmd.cancel";

    private String CMD_CONVERT = "cmd.convert";

    private String CMD_BROWSE = "cmd.browse";

    private String CMD_HELP = "cmd.help";

    private JTextField sourceFilePathField = null;

    private Frame parent = null;
    

    /**
     * Create a new LoginDialog
     */
    public ConverterGUI(Frame frame, boolean modal) {
        super((Frame) frame, modal);
        parent = frame;
        initComponents();
        System.out.println("Ready.");
    }

    private void initComponents() {

        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            //e.printStackTrace();
        }

        Container contents = getContentPane();
        
        contents.setLayout(new BorderLayout());
        
        JLabel pixLabel = new JLabel(new ImageIcon(loadImage("rc/JF_96x96.png")));
        contents.add(BorderLayout.WEST,pixLabel);
        
       
       
        JPanel contentPanel = new JPanel();
        contentPanel.setOpaque(false);
        contents.add(BorderLayout.CENTER,contentPanel);
        contentPanel.setLayout(new GridBagLayout());
        
        Console console = new Console();
        contents.add(BorderLayout.SOUTH,console.createArea());
        
        String version = getClass().getPackage().getImplementationVersion();
        if(version==null){
            version = "SNAPSHOT";
        }
        setTitle("MQL2JFOREX Converter v."+version);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent event) {
                // user hit window manager close button <---
                System.exit(0);
            }
        });

        setIconImage(loadImage("com/sun/java/swing/plaf/windows/icons/Inform.gif"));

        contentPanel.add(new JLabel("Path to MQL4 file:"), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

        sourceFilePathField = new JTextField("...");
        sourceFilePathField.setPreferredSize(new Dimension(300, 25));
        sourceFilePathField.setEditable(false);
        contentPanel.add(sourceFilePathField, new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

        JButton buttonBrowse = new JButton("Browse...");
        buttonBrowse.setActionCommand(CMD_BROWSE);
        buttonBrowse.addActionListener(this);
        contentPanel.add(buttonBrowse, new GridBagConstraints(1, 1, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
        
        
        JPanel panel = new JPanel();
        panel.setOpaque(false);
        JButton buttonOK = new JButton("Convert");
        buttonOK.setActionCommand(CMD_CONVERT);
        buttonOK.addActionListener(this);
        panel.add(buttonOK);
        
        JButton buttonCancel = new JButton("Cancel");
        buttonCancel.setActionCommand(CMD_CANCEL);
        buttonCancel.addActionListener(this);
        panel.add(buttonCancel);
        
        
       

        
        JButton buttonHelp = new JButton("Help");
        buttonHelp.setActionCommand(CMD_HELP);
        buttonHelp.addActionListener(this);
        panel.add(buttonHelp);

        contentPanel.add(panel, new GridBagConstraints(0, 2, 2, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

        /*
        gridx - The initial gridx value.
        gridy - The initial gridy value.
        gridwidth - The initial gridwidth value.
        gridheight - The initial gridheight value.
        weightx - The initial weightx value.
        weighty - The initial weighty value.
        anchor - The initial anchor value.
        fill - The initial fill value.
        insets - The initial insets value.
        ipadx - The initial ipadx value.
        ipady - The initial ipady value.
        */

        int w = (int) (getParent().getLocation().getX());
        int h = (int) (getParent().getLocation().getY());

        setLocation(w - 250, h - 300);
        
        setAlwaysOnTop(true);

    } // initComponents()

    private void browse() {
        JFileChooser chooser = new JFileChooser();
        // Note: source for ExampleFileFilter can be found in FileChooserDemo,
        // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
        FileFilter filter = new FileFilter() {
            @Override
            public String getDescription() {
                return "MQL4 file";
            }

            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() || pathname.getAbsolutePath().toUpperCase().endsWith(".MQ4");
            }
        };

        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(parent);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File selectedFile = chooser.getSelectedFile();
            System.out.println("You chose to convert this file:\n" + selectedFile.getAbsolutePath());
            sourceFilePathField.setText(selectedFile.getAbsolutePath());
        }
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {

        String cmd = actionEvent.getActionCommand();

        if (cmd == null) {
            // do nothing
        } else if (cmd.equals(CMD_CANCEL)) {
            System.exit(0);
        } else if (cmd.equals(CMD_CONVERT)) {
           
            File srcFile = new File(sourceFilePathField.getText());
            System.out.println("Converting: "+(sourceFilePathField.getText()));
            if (srcFile.exists() && srcFile.isFile()) {
                MQLConverter converter = new MQLConverter();
                try {
                    File result = converter.convert(srcFile.getAbsolutePath());
                    //JOptionPane.showMessageDialog(parent,, "Ok", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("File converted to "+result.getAbsolutePath()+".\nMake sure you have last jftoolbox jar file in "+(converter.getMyStrategiesDefaultDirPath()+File.separator+"files"));
                } catch (Exception e) {
                    System.out.println("Unable to convert.");
                    //JOptionPane.showMessageDialog(parent, e.getMessage(), "Unable to convert.", JOptionPane.WARNING_MESSAGE);
                    e.printStackTrace();
                }
            }else{
                System.out.println("File not found: "+(srcFile.getAbsolutePath()));
                flushField(sourceFilePathField);
            }
        } else if (cmd.equals(CMD_BROWSE)) {
            browse();
        } else if (cmd.equals(CMD_HELP)) {
            try {
                Desktop.getDesktop().browse(new URI("http://www.dukascopy.com/jforex/"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * This main() is provided for debugging purposes, to display a sample
     * dialog.
     */
    public static void main(String args[]) {
        JFrame frame = new JFrame();

        frame.setPreferredSize(new Dimension(200, 100));

        Toolkit toolkit = Toolkit.getDefaultToolkit();
        // Get the current screen size
        Dimension scrnsize = toolkit.getScreenSize();
        frame.setLocation((int) scrnsize.getWidth() / 2, (int) scrnsize.getHeight() / 2);

        frame.setTitle("Parent frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setVisible(false);

        JDialog dialog = new ConverterGUI(frame, true);
        dialog.setPreferredSize(new Dimension(500, 500));
        dialog.pack();
        dialog.setVisible(true);
    }
    public void flushField(JComponent field) {

        Component[] components = field.getParent().getComponents();
        for (int i = 0; i < components.length; i++) {

            if (components[i].equals(field)) {
                JComponent textField = ((JComponent) components[i]);

                Color originalColor = textField.getBackground();

                try {
                    textField.setBackground(Color.RED);
                    textField.repaint();
                    RepaintManager.currentManager(textField).paintDirtyRegions();
                    Thread.sleep(300);
                    textField.setBackground(originalColor);
                    textField.repaint();
                    RepaintManager.currentManager(textField).paintDirtyRegions();
                    Thread.sleep(300);
                    textField.setBackground(Color.RED);
                    textField.repaint();
                    RepaintManager.currentManager(textField).paintDirtyRegions();
                    Thread.sleep(300);

                } catch (Exception e) {

                }

                textField.setBackground(originalColor);
            }
        }
    }

    public static Image loadImage(final String path) {
        Image rc = null;
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            turboPipe(inputStream, arrayOutputStream);
            rc = Toolkit.getDefaultToolkit().createImage(arrayOutputStream.toByteArray());
            inputStream.close();
        } catch (Throwable e) {
            System.out.println(e.getMessage());
        }
        return rc;
    }

    public static int turboPipe(InputStream inputStream, OutputStream outputStream) {

        if (inputStream == null || outputStream == null)
            return 0;

        byte[] buffer = new byte[4 * 1024];
        int bytes_read;
        int counter = 0;
        try {
            while (true) {
                bytes_read = inputStream.read(buffer);
                if (bytes_read == -1) {
                    break;
                }
                outputStream.write(buffer, 0, bytes_read);
                counter += bytes_read;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return counter;
    }
    
    

}
